<!-- 见证任务分配 -->
<template>
  <div class="witness-body">
    <breadcrumb
      :bread-path-list="breadPathList"
      last-bread-title="项目操作日志"
      :show-back-btn-flag="true"
      @handleBack="handleBack"
    />
    <div class="box">
      当前任务：
      <span>{{ projectName }}</span>
    </div>
    <div class="layout-wrapper layout-witness">
      <div class="box_box">
        <div class="layout-header layout-search">
          <el-form :inline="true" :model="searchForm">
            <el-form-item label="操作主体">
              <el-select
                v-model="searchForm.operateUserRole"
                class="ui-w180"
                option-max-width="180px"
                placeholder="请选择"
                clearable
                @change="handleSearchFn()"
              >
                <!-- <el-option key label="全部" value></el-option> -->
                <el-option
                  v-for="item in operateUserRoleArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="操作类型">
              <el-select
                v-model="searchForm.operateType"
                class="ui-w180"
                option-max-width="180px"
                placeholder="请选择"
                clearable
                @change="handleSearchFn()"
              >
                <el-option v-for="item in operateTypeArr" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="操作时间">
              <el-date-picker
                v-model="searchForm.date"
                class="ui-w260"
                unlink-panels
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :clearable="true"
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptions"
                @change="handleSearchFn()"
              />
            </el-form-item>
            <el-form-item class="rigthText">
              <el-input
                v-model.trim="searchForm.keywords"
                class="ui-w320"
                placeholder="请输入内容"
                @keyup.native.enter="handleSearchFn()"
              >
                <el-button slot="append" type="primary" icon="icon-sousuo" @click="handleSearchFn()" />
              </el-input>
            </el-form-item>
          </el-form>
        </div>
        <div class="layout-body">
          <el-table ref="taskTable" v-loading="tableLoading" :data="tableData" height="100%" stripe>
            <el-table-column type="index" align="left" label="序号" width="50">
              <template slot-scope="scope">
                {{ (pageObj.currentPage - 1) * pageObj.pageSize + scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column prop="operateTime" label="操作时间" min-width="80" />
            <el-table-column
              prop="operateUserRoleName"
              label="操作主体"
              min-width="80"
              :formatter="formatterOperateUserRoleName"
            />
            <el-table-column prop="operateUserName" label="操作账号" min-width="80" />
            <el-table-column prop="operateType " label="操作类型" min-width="80" :formatter="formatterOperateType" />
            <el-table-column prop="bidSectionName" label="操作标段" min-width="150" show-overflow-tooltip />
            <el-table-column prop="operateDesc" label="操作内容" min-width="300" show-overflow-tooltip />
          </el-table>
        </div>
      </div>
    </div>
    <div class="layout-footer">
      <pagination
        v-if="pageObj.total > pageObj.pageSizes[0]"
        :total="pageObj.total"
        :page.sync="pageObj.currentPage"
        :limit.sync="pageObj.pageSize"
        :page-sizes="pageObj.pageSizes"
        @pagination="operateListFn()"
      />
    </div>
    <!-- 项目详情弹窗 -->
    <!-- <ProjectDetailsDialog :visible.sync="detailDialogShow" :projectId="currentProjectId" :taskObj="TASKOBJ" /> -->
    <ProjectDetailsDrawer
      :visible.sync="detailDialogShow"
      @closeDrawer="closeDrawerFn"
      :project-id="currentProjectId"
      :task-obj="TASKOBJ"
    />
  </div>
</template>
<script>
  // 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
  import { moduleInit, operateList } from "../../../api/api";
  import { FindArrayFn, getFirstAndSecondLevel } from "../../../utils/utils";
  // import ProjectDetailsDialog from "../../../components/dialog/ProjectDetailsDialog.vue";
  import ProjectDetailsDrawer from "../../../components/dialog/ProjectDetailsDrawer.vue";
  export default {
    // 引入组件
    components: { ProjectDetailsDrawer },
    props: {},
    data() {
      // 这里存放数据
      return {
        breadPathList: [
          {
            path: "/WitnessLogController",
            title: "操作日志"
          }
        ],
        currentWitness: {},
        assignData: [],
        operateUserRoleArr: [],
        operateTypeArr: [],
        assignShow: false,
        assignTitle: "",
        assignType: "",
        projectName: "",
        witnessTaskId: "",
        searchForm: {
          operateUserRole: "",
          operateType: "",
          date: [
            // this.$moment(new Date()).format("yyyy-MM-DD"),
            // this.$moment(new Date()).format("yyyy-MM-DD"),
          ],
          keywords: ""
        },
        TASKOBJ: {}, // 后端返回的所有下拉映射值数据
        tenderModeIndustryObj: {}, // 依据行业类别一级菜单分组显示的交易方式
        tenderModeOptionsObj: {}, // 交易方式下拉
        tableData: [],
        tableLoading: false,
        pageObj: {
          total: 0,
          currentPage: 1,
          pageSize: 10,
          pageSizes: [10, 20, 30]
        },
        detailDialogShow: false, // 是否展示项目详情弹窗
        currentProjectId: "", // 当前操作的项目id
        pickerOptions: {
          shortcuts: [
            {
              text: "最近一周",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "最近一个月",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "最近三个月",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                picker.$emit("pick", [start, end]);
              }
            }
          ]
        }
      };
    },
    // 监听属性 类似于data概念
    computed: {},
    // 监控data中的数据变化
    watch: {},
    // 生命周期 - 创建完成（可以访问当前this实例）
    created() {
      this.projectName = this.$route.query.projectName;
      this.witnessTaskId = this.$route.query.witnessTaskId;
      this.moduleInitFn();
      this.handleSearchFn();
    },
    // 生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {},
    // 生命周期 - 销毁之前
    beforeDestroy() {},
    // 生命周期 - 销毁完成
    destroyed() {},
    // 如果页面有keep-alive缓存功能，这个函数会触发
    activated() {},
    // 方法集合
    methods: {
      closeDrawerFn() {
        console.log("closeDrawerFn");
        this.currentProjectId = "";
        this.detailDialogShow = false;
      },
      async moduleInitFn() {
        const p = { moduleName: "LOG" };
        try {
          const res = await moduleInit(p);
          if (res.success) {
            this.TASKOBJ = res.data;
            for (const key in res.data.operateType) {
              if (Object.hasOwnProperty.call(res.data.operateType, key)) {
                const item = res.data.operateType[key];
                this.operateTypeArr.push({
                  label: item.label,
                  value: item.value
                });
              }
            }
            for (const key in res.data.operateUserRole) {
              if (Object.hasOwnProperty.call(res.data.operateUserRole, key)) {
                const item = res.data.operateUserRole[key];
                this.operateUserRoleArr.push({
                  label: item.label,
                  value: item.value
                });
              }
            }
          } else {
            this.$message({
              type: "error",
              message: res.message || "获取数据失败，请稍后再试",
              single: true
            });
          }
        } catch (err) {
          console.error(err);
          this.$message({
            type: "error",
            message: "获取数据失败，请稍后再试",
            single: true
          });
        }
      },
      // 行业类别发生变化，交易方式下拉选项联动
      industryChange(arr) {
        const obj = getFirstAndSecondLevel(arr);
        this.searchForm.industrySecondLevel = obj.secondLevel;
        this.tenderModeOptionsObj = {};
        if (obj.firstLevel.length === 0) {
          // 1. 当行业类型没有值时，交易方式默认返回所有的下拉值
          for (const key in this.tenderModeIndustryObj) {
            this.tenderModeOptionsObj = this.getTenderModeOptions(
              this.tenderModeOptionsObj,
              this.tenderModeIndustryObj[key]
            );
          }
        } else {
          // 2. 有值时，依据一级行业的一级菜单获取交易方式的下拉
          for (let i = 0; i < obj.firstLevel.length; i++) {
            this.tenderModeOptionsObj = this.getTenderModeOptions(
              this.tenderModeOptionsObj,
              this.tenderModeIndustryObj[obj.firstLevel[i]]
            );
          }
        }
        this.handleSearchFn();
      },
      getTenderModeOptions(obj, arr) {
        for (let i = 0; i < arr.length; i++) {
          // eslint-disable-next-line no-prototype-builtins
          if (!obj.hasOwnProperty(arr[i].value)) {
            obj[arr[i].value] = arr[i].label;
          }
        }
        return obj;
      },
      // 搜索查询
      handleSearchFn() {
        this.pageObj.total = 0;
        this.pageObj.currentPage = 1;
        this.operateListFn();
      },
      // 见证操作日志列表查询
      async operateListFn() {
        try {
          this.tableLoading = true;
          this.tableData = [];
          const params = {
            projectId: this.witnessTaskId,
            operateUserRole: this.searchForm.operateUserRole, // 操作主体
            operateType: this.searchForm.operateType, // 操作类型
            search: this.searchForm.keywords,
            currentPage: this.pageObj.currentPage,
            pageSize: this.pageObj.pageSize
          };
          if (this.searchForm.date && this.searchForm.date.length) {
            params.startTime = `${this.searchForm.date[0]} 00:00:00`;
            params.endTime = `${this.searchForm.date[1]} 23:59:59`;
          } else {
            params.startTime = "";
            params.endTime = "";
          }
          const res = await operateList(params);
          this.tableLoading = false;
          if (res.success) {
            if (res.data.data.length === 0 && this.pageObj.currentPage !== 1) {
              this.pageObj.currentPage = 1;
              this.$nextTick(() => {
                this.operateListFn();
              });
              return;
            }
            this.tableData = res.data.data;
            console.log(this.tableData, "-------------------1");
            this.pageObj.total = res.data.pageBean.count;
          } else {
            this.$message({
              type: "error",
              message: res.message || "获取数据失败，请稍后再试",
              single: true
            });
          }
        } catch (error) {
          console.log(error);
          this.tableLoading = false;
        }
      },
      // 返回方法
      handleBack() {
        this.$router.push({ path: "/WitnessLogController" });
      },
      // 设置表格单元格样式
      handleCellClassName({ row, columnIndex }) {
        // 由于第2、3、4、5、6列进行了单元格合并，使用的是当前标段第一行的border，故不需要变细
        let className = "";
        if (
          row.thinBorder &&
          columnIndex !== 1 &&
          columnIndex !== 2 &&
          columnIndex !== 3 &&
          columnIndex !== 4 &&
          columnIndex !== 5
        ) {
          className = "in-Table-cell";
        }
        return className;
      },
      formatterOperateUserRoleName(row) {
        let str = "";
        if (row.operateUserRoleName) {
          this.operateUserRoleArr.map((ele) => {
            if (row.operateUserRoleName === ele.value) {
              str = ele.label;
            }
          });
        }
        return str;
      },
      formatterOperateType(row) {
        let str = "";
        if (row.operateType) {
          this.operateTypeArr.map((ele) => {
            if (row.operateType === ele.value) {
              str = ele.label;
            }
          });
        }
        return str;
      },
      formatterQualificationExamMethod(row) {
        let str = "";
        if (row.qualificationExamMethod) {
          const obj = FindArrayFn(this.TASKOBJ.qualificationExamMethods, row.qualificationExamMethod);
          str = obj.label;
        }
        return str;
      }
    }
  };
</script>
<style lang="scss" scoped>
  .box_box {
    height: 100%;
    margin: 10px;
    padding: 10px;
    padding-bottom: 0;
    margin-bottom: 0;
    background: #fff !important;
  }
  .layout-footer {
    margin-top: 0 !important;
    padding-top: 0 !important;
    margin: 10px;
    background: #fff;
    padding-bottom: 10px;
  }
  .witness-result {
    width: 76px;
    height: 20px;
    line-height: 20px;
    background: #fc9306;
    border-radius: 10px;
    color: #fff;
    font-size: 12px;
    text-align: center;
  }
  .box {
    border-top: 1px solid #ededed;
    padding: 10px;
    height: 20px;
    background: #fff;
    span {
      font-weight: 700;
    }
  }
  .rigthText {
    float: right;
    padding-right: 10px;
    // margin-left: 430px !important;
  }
</style>
